package com.cmcc.aregister.ui.activity;

import java.io.IOException;
import java.net.MalformedURLException;
import java.sql.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.appointmentregister.sina.AccessToken;
import com.appointmentregister.sina.DialogError;
import com.appointmentregister.sina.ShareActivity;
import com.appointmentregister.sina.Utility;
import com.appointmentregister.sina.Weibo;
import com.appointmentregister.sina.WeiboDialogListener;
import com.appointmentregister.sina.WeiboException;
import com.appointmentregister.sina.WeiboParameters;
import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.constant.Arguments;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.cmcc.aregister.cs.constant.GlobalSetting;
import com.cmcc.aregister.cs.database.DatabaseAdapter;
import com.cmcc.aregister.cs.http.HttpAsyncTask;
import com.cmcc.aregister.cs.model.UpdateEntity;
import com.cmcc.aregister.cs.util.PotoalParcelable;
import com.cmcc.aregister.cs.util.UniqueKey;
import com.cmcc.sdk.CmccDataStatistics;
import com.oauth.utils.ConfigUtil;
import com.oauth.utils.FileHelper;

public class MoreActivity extends LoginParentActivity
{
    // ------view------
    private final String TAG = "MoreActivity";
    private Button top_left_image;
    private LinearLayout userLoginLayout, one39Layout, ydzqLayout, weiboLayout,
        msgLayout, help_layout, feedback_layout, versionInfoLayout,
        msg_center_layout, update_version_layout, notice_layout,
        add_bankcard_layout, user_guide_layout, yichengtong_layout;
    private CheckBox infoVisibleCB;
    boolean isSet = false;
    private PopupWindow popupWindow;
    private int screenWidth;
    private int screenHeight;
    private String result;
    private String url;
    private int status;
    private String message;
    private ConfigUtil conf = ConfigUtil.getInstance();
    private String sinaAccessToken = "";
    private String sinaSccessTokenSecret = "";
    private String qqAccessToken = "";
    private String qqAccessTokenSecret = "";
    private String params = "";
    private boolean isAuth = false;
    private boolean isLogin = false;
    private boolean isLogoutClick = false;
    Intent intent = null;
    private ImageView loginImage;
    private TextView loginTxt;
    private DatabaseAdapter mDatabaseAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "------onCreate------");
        }
        init(R.layout.p_more);
        mHttpManager.setCxt(getParent());
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "------onDestroy------");
        }
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "------onPause------");
        }
    }

    @Override
    protected void onRestart()
    {
        super.onRestart();
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "------onRestart------");
        }
    }

    private void isLoginTimeout()
    {
        mDatabaseAdapter.open_user();
        Cursor c = mDatabaseAdapter.fetchAllUserData();
        if (c != null)
        {
            c.moveToFirst();
            if (c.getCount() > 0)
            {
                String date = c.getString(c.getColumnIndex("login_date"));
                try
                {
                    date = UniqueKey.decodeStr(date);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                String loginDate = new Date(Long.parseLong(date)).toString();
                long dateMillis = System.currentTimeMillis();
                String now = new Date(dateMillis).toString();
                SharedPreferences mSharedPreferences = getSharedPreferences(
                    ConfigUtilHelper.INFO_VISIBLE_PREFS, Context.MODE_PRIVATE);
                Editor edit = mSharedPreferences.edit();
                if (loginDate.equals(now))
                {
                    edit.putBoolean(ConfigUtilHelper.IS_LOGIN, true);
                }
                else
                {
                    edit.putBoolean(ConfigUtilHelper.IS_LOGIN, false);
                    mDatabaseAdapter.deleteAllUserData();
                }
                edit.commit();
            }
        }
        c.close();
        mDatabaseAdapter.close_user();
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "------onResume------");
        }
        isLoginTimeout();

        // SharedPreferences mSharedPreferences =
        // getSharedPreferences(ConfigUtilHelper.INFO_VISIBLE_PREFS,
        // Context.MODE_PRIVATE);
        // isLogin = mSharedPreferences.getBoolean(ConfigUtilHelper.IS_LOGIN,
        // false);
        isLogin = ConfigUtilHelper.isLogin(this);
        if (isLogin)
        {
            loginImage.setImageResource(R.drawable.regist_logout);
            loginTxt.setText(getString(R.string.user_logout));
        }
        else
        {
            loginImage.setImageResource(R.drawable.regist_login);
            loginTxt.setText(getString(R.string.login_title));
        }
    }

    @Override
    protected void onStart()
    {
        super.onStart();
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "------onStart------");
        }
    }

    @Override
    protected void onStop()
    {
        super.onStop();
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "------onStop------");
        }
    }

    @Override
    protected void setupData()
    {
        mDatabaseAdapter = new DatabaseAdapter(this);
        SharedPreferences infoVisiblePre = getSharedPreferences(
            ConfigUtilHelper.INFO_VISIBLE_PREFS, Context.MODE_PRIVATE);
        isSet = infoVisiblePre.getBoolean(ConfigUtilHelper.info_visible_set,
            false);
        if (ConfigUtilHelper.debug)
        {
            if (isSet)
                Log.i(TAG, "------isSet------->" + true);
            else
            {
                Log.i(TAG, "------isSet------->" + false);
            }
        }
    }

    @Override
    protected void setupView()
    {
        ((ImageView) findViewById(R.id.title))
            .setBackgroundResource(R.drawable.more_title);
        // ((TextView) findViewById(R.id.title)).setText(R.string.more);
        top_left_image = (Button) findViewById(R.id.top_left_image);

        userLoginLayout = (LinearLayout) findViewById(R.id.user_login_layout);
        // infoVivsibleLayout = (LinearLayout)
        // findViewById(R.id.info_visible_set_layout);

        msg_center_layout = (LinearLayout) findViewById(R.id.msg_center_layout);
        update_version_layout = (LinearLayout) findViewById(R.id.update_version_layout);

        loginImage = (ImageView) findViewById(R.id.login_image);
        loginTxt = (TextView) findViewById(R.id.login_text);
        help_layout = (LinearLayout) findViewById(R.id.help_layout);
        feedback_layout = (LinearLayout) findViewById(R.id.feedback_layout);
        notice_layout = (LinearLayout) findViewById(R.id.notice_layout);
        ydzqLayout = (LinearLayout) findViewById(R.id.ydzq_layout);
        one39Layout = (LinearLayout) findViewById(R.id.one39_layout);
        weiboLayout = (LinearLayout) findViewById(R.id.weibo_layout);
        msgLayout = (LinearLayout) findViewById(R.id.msg_layout);
        versionInfoLayout = (LinearLayout) findViewById(R.id.version_info_layout);
        add_bankcard_layout = (LinearLayout) findViewById(R.id.add_bankcard_layout);
        user_guide_layout = (LinearLayout) findViewById(R.id.user_guide_layout);
        yichengtong_layout = (LinearLayout) findViewById(R.id.yichengtong_layout);
        infoVisibleCB = (CheckBox) findViewById(R.id.info_visible_checkbox);
        infoVisibleCB.setOnCheckedChangeListener(onCheckedChangeListener);
        if (isSet)
        {
            infoVisibleCB.setChecked(true);
        }
        else
        {
            infoVisibleCB.setChecked(false);
        }

        top_left_image.setVisibility(View.VISIBLE);
        top_left_image.setOnClickListener(onClickListener);

        userLoginLayout.setOnClickListener(onClickListener);
        // infoVivsibleLayout.setOnClickListener(onClickListener);
        help_layout.setOnClickListener(onClickListener);
        feedback_layout.setOnClickListener(onClickListener);
        notice_layout.setOnClickListener(onClickListener);
        one39Layout.setOnClickListener(onClickListener);
        ydzqLayout.setOnClickListener(onClickListener);
        weiboLayout.setOnClickListener(onClickListener);
        msgLayout.setOnClickListener(onClickListener);
        versionInfoLayout.setOnClickListener(onClickListener);
        msg_center_layout.setOnClickListener(onClickListener);
        update_version_layout.setOnClickListener(onClickListener);
        add_bankcard_layout.setOnClickListener(onClickListener);
        user_guide_layout.setOnClickListener(onClickListener);
        yichengtong_layout.setOnClickListener(onClickListener);
        feedback_layout.setVisibility(View.GONE);
    }

    OnCheckedChangeListener onCheckedChangeListener = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
            boolean isChecked)
        {
            // TODO Auto-generated method stub
            if (ConfigUtilHelper.debug)
            {
                Log.i(TAG, "-----onCheckedChanged--------");
            }
            SharedPreferences infoVisiblePre = getSharedPreferences(
                ConfigUtilHelper.INFO_VISIBLE_PREFS, Context.MODE_PRIVATE);
            Editor edit = infoVisiblePre.edit();
            if (infoVisibleCB.isChecked())
            {
                if (ConfigUtilHelper.debug)
                {
                    Log.i(TAG, "-----isChecked--------");
                }
                edit.putBoolean(ConfigUtilHelper.info_visible_set, true);
            }
            else
            {
                if (ConfigUtilHelper.debug)
                {
                    Log.i(TAG, "--not---isChecked--------");
                }
                edit.putBoolean(ConfigUtilHelper.info_visible_set, false);
            }
            edit.commit();
        }
    };

    OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View v)
        {
            int id = v.getId();
            switch (id)
            {
            case R.id.help_layout:
                gotoHelpActivity();
                break;
            case R.id.notice_layout:
                goNotice();
                break;
            case R.id.feedback_layout:
                gotoFeedbackActivity();
                break;
            case R.id.top_left_image:
                // goback home;
                gobackHome();
                break;
            case R.id.user_login_layout:
                if (isLogin)
                {
                    if (connectedNetwork())
                    {
                        showAlertLogoutDlg(getString(R.string.notice),
                            getString(R.string.logout_msg),
                            getString(R.string.logout_yes),
                            getString(R.string.logout_no));
                    }
                    else
                    {
                        checkInternet();
                    }
                }
                else
                {
                    gotoLogin();
                    // ConfigUtilHelper.removeData(MoreActivity.this);
                }
                break;
            case R.id.one39_layout:
                if (connectedNetwork())
                {
                    load139Website();
                }
                else
                {
                    checkInternet();
                }
                break;
            case R.id.ydzq_layout:
                if (connectedNetwork())
                {
                    loadYdzqWebsite();
                }
                else
                {
                    checkInternet();
                }
                break;
            case R.id.weibo_layout:
                getPopupWindow();
                popupWindow.showAtLocation(findViewById(R.id.p_more_parent),
                    Gravity.BOTTOM, 0, 0);
                popupWindow.update();
                break;
            case R.id.msg_layout:
                try
                {
                    // Intent i = new Intent(Intent.ACTION_SEND);
                    // i.setType("plain/text");
                    // i.putExtra(Intent.EXTRA_SUBJECT,getString(R.string.email_subject));
                    // i.putExtra(Intent.EXTRA_TEXT,
                    // getString(R.string.weibo_default_words));
                    // startActivity(Intent.createChooser(i,getString(R.string.choice_email)));
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_SEND);
                    intent.setType("*/*");
                    // intent.putExtra(Intent.EXTRA_SUBJECT,getString(R.string.email_subject));
                    // intent.putExtra(Intent.EXTRA_TEXT,
                    // getString(R.string.weibo_default_words));
                    // intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
                    intent.putExtra(Intent.EXTRA_TEXT,
                        getString(R.string.weibo_default_words));
                    startActivity(intent);
                }
                catch (Exception e)
                {
                    showMsg(R.string.no_choice_email);
                }
                break;
            case R.id.version_info_layout:
                gotoVersionInfo();
                break;

            case R.id.sina_weibo_btn:
                // conf.setCurWeibo(ConfigUtil.SINAW);
                // conf.initSinaData();
                // showProgressDlg(getString(R.string.notice),
                // getString(R.string.dialog_loading));
                // 询问是否进入上次登录的账户
                String access = ConfigUtil.getSinaToken(MoreActivity.this);
                if (access != null)
                {
                    showAlertDlg_sina(getString(R.string.dialog_warning),
                        getString(R.string.dialog_goto_last_user),
                        getString(R.string.dialog_yes),
                        getString(R.string.dialog_no));
                }
                else
                {
                    sinaShare();
                }
                closeDlg();
                break;
            case R.id.qq_weibo_btn:
                conf.setCurWeibo(ConfigUtil.QQW);
                conf.initQqData();
                showProgressDlg(getString(R.string.notice),
                    getString(R.string.dialog_loading));
                closeDlg();
                break;
            case R.id.cancel_btn:
                closeDlg();
                break;
            case R.id.msg_center_layout:
                break;
            case R.id.add_bankcard_layout:
                addBankCardActivity();
                break;
            case R.id.update_version_layout:
                if (ConfigUtilHelper.isConnectingToInternet(MoreActivity.this))
                {
                    new GetDataTask().execute();
                }
                else
                {
                    checkInternet();
                }
                break;
            case R.id.user_guide_layout:
                userGuide();
                break;
            case R.id.yichengtong_layout:
                yichengtong();
                break;
            }
        }
    };

    private UpdateEntity mUpdateEntity = new UpdateEntity();

    private class GetDataTask extends AsyncTask<Void, Void, String[]>
    {

        // 任务在后台执行
        @Override
        protected String[] doInBackground(Void... params)
        {
            // String appkey = getString(R.string.SZICITY_APPKEY);
            // String channel = getString(R.string.SZICITY_CHANNEL);
            String appversion = ConfigUtilHelper
                .getVersionName(getApplication());
            String url = Arguments.CHECK_UPDATE_URL;
            if (ConfigUtilHelper.debug)
            {
                Log.i(TAG, "升级url：" + url);
            }
            mUpdateEntity = ConfigUtilHelper.getUpdateMsg(url, "8",
                "wxcityMobileClient", "2", appversion);
            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values)
        {
            // TODO Auto-generated method stub
            super.onProgressUpdate(values);

        }

        @Override
        protected void onPreExecute()
        {
            showProgressDialogUpdate();
        }

        // 任务执行的结果
        @Override
        protected void onPostExecute(String[] result)
        {
            dismissProgressDialog();
            String appversion = ConfigUtilHelper
                .getVersionName(getApplication());
            if (mUpdateEntity.Status != null
                && mUpdateEntity.Status.equals("1"))
            {
                if (mUpdateEntity.State.equals("0"))
                {
                    showAlertDlg_update(
                        getString(R.string.dialog_update_title),
                        mUpdateEntity.Content,
                        getString(R.string.dialog_update_later),
                        getString(R.string.dialog_update_now),
                        mUpdateEntity.DownLink);
                }
                else if (mUpdateEntity.State.equals("1"))
                {
                    showAlert_update(getString(R.string.dialog_update_title),
                        mUpdateEntity.Content,
                        getString(R.string.dialog_update_now),
                        mUpdateEntity.DownLink);

                }
                else if (appversion.equals(mUpdateEntity.VersionNum))
                {
                    showSingleAlertDlg(getString(R.string.dialog_update_title),
                        getString(R.string.dialog_update_no_new),
                        getString(R.string.dialog_close));
                }
            }
            else
            {
                showSingleAlertDlg(getString(R.string.dialog_update_title),
                    getString(R.string.dialog_update_no_new),
                    getString(R.string.dialog_close));
            }
        }
    }

    /**
     * 调用浏览器下载新版本
     */
    public void nagativeDoWorkUpdate(String url)
    {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse(url);
        intent.setData(content_url);
        startActivity(intent);
    }

    private void share()
    {

        SharedPreferences preferences = getSharedPreferences(
            FileHelper.PREFERENCES_NAME, Activity.MODE_PRIVATE);
        if (conf.getCurWeibo().equals(ConfigUtil.SINAW))
        {
            sinaAccessToken = preferences.getString("sinaAccessToken", "");
            sinaSccessTokenSecret = preferences.getString("sinaAccessSecret",
                "");
            if (!sinaAccessToken.equals("")
                && !sinaSccessTokenSecret.equals(""))
            {
                if (ConfigUtilHelper.debug)
                {
                    Log.v(TAG, "--sina--accessToken != null------"
                        + sinaAccessToken);
                }
                isAuth = true;
            }
            else
            {
                isAuth = false;
            }

        }
        else if (conf.getCurWeibo().equals(ConfigUtil.QQW))
        {
            qqAccessToken = preferences.getString("qqAccessToken", "");
            qqAccessTokenSecret = preferences.getString("qqAccessSecret", "");
            if (!qqAccessToken.equals("") && !qqAccessTokenSecret.equals(""))
            {
                if (ConfigUtilHelper.debug)
                {
                    Log.v(TAG, "--qq--accessToken != null------"
                        + qqAccessToken);
                }
                isAuth = true;
            }
            else
            {
                isAuth = false;
            }
        }
    }

    private void checkInternet()
    {
        showSingleAlertDlg(getString(R.string.dialog_warning),
            getString(R.string.dialog_check_internet),
            getString(R.string.dialog_close));
    }

    private void goNotice()
    {
        Intent intent = new Intent(MoreActivity.this, NoticeActivity.class);
        intent.putExtra(Arguments.NOTICE_JUMP_TYPE,
            Arguments.NOTICE_JUMP_TYPE_MORE);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    // 医程通
    private void yichengtong()
    {
        Intent intent = new Intent(MoreActivity.this, YichengtongActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    // 用户指南
    private void userGuide()
    {
        Intent intent = new Intent(MoreActivity.this, UserGuideActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    // 加载139社区
    private void load139Website()
    {
        Intent intent = new Intent(MoreActivity.this, One39WebsiteLoading.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    // 加载移动专区
    private void loadYdzqWebsite()
    {
        Intent intent = new Intent(MoreActivity.this, YdzqWebsiteLoading.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    // 回到主界面
    private void gobackHome()
    {
        Intent intent = new Intent(MoreActivity.this, NewIndexActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }

    // 跳转到登陆界面
    private void gotoLogin()
    {
        Intent intent = new Intent(MoreActivity.this, UserLoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    // 跳转到登陆界面
    private void gotoVersionInfo()
    {
        Intent intent = new Intent(MoreActivity.this, VersionInfo.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    // 跳转到帮助界面
    private void gotoHelpActivity()
    {
        Intent intent = new Intent(MoreActivity.this, HelpActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    // 跳转到反馈界面
    private void gotoFeedbackActivity()
    {
        Intent intent = new Intent(MoreActivity.this, FeedbackActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    private HttpAsyncTask queryBindCardTask;

    private void addBankCardActivity()
    {
        params = "cid=8&token=wxcityMobileClient&mid="
            + ConfigUtilHelper.getMobile(app);
        queryBindCardTask = new HttpAsyncTask(HttpAsyncTask.POST,
            GlobalSetting.XML_GET_BINDCARD, Arguments.CHECK_BIND_URL, params,
            HttpAsyncTask.CACHE_TYPE_ACTION, true);
        showProgressDialogNew(R.string.load_wap);
        queryBindCardTask.setUIHandler(queryBindCardTaskHandler);
        mHttpManager.execute(queryBindCardTask);
    }

    private Handler queryBindCardTaskHandler = new Handler() {
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                dismissProgressDialog();
                if (msg.obj != null)
                {
                    Map<String, Object> map = (Map<String, Object>) msg.obj;
                    String status = (String) map.get(Arguments.XML_STATUS);
                    String cardNum = (String) map.get("cardNum");
                    String userId = (String) map.get("userId");
                    String bindId = (String) map.get("bindUserId");
                    Intent intent_1 = new Intent(MoreActivity.this,
                        BindBankCardActivity.class);
                    Map<String, Object> httpMap = new HashMap<String, Object>();
                    httpMap.put("status", status);
                    httpMap.put("cardNum", cardNum);
                    httpMap.put("bindId", bindId);
                    httpMap.put("userId", userId);
                    PotoalParcelable potoal = new PotoalParcelable(httpMap);
                    intent_1.putExtra(Arguments.INTENT_TO_NEXT_PAGE, potoal);
                    intent_1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent_1);
                }
                else
                {
                    showMsg(R.string.read_member_fail);
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.get_bind_info_err),
                    getString(R.string.close));
                break;
            }
        };
    };

    private void closeDlg()
    {
        if (popupWindow != null)
        {
            popupWindow.dismiss();
            popupWindow = null;
        }
    }

    /*
     * 获取PopupWindow实例
     */
    private void getPopupWindow()
    {

        if (null != popupWindow)
        {
            popupWindow.dismiss();
            popupWindow = null;
            return;
        }
        else
        {
            initPopuptWindow();
        }
    }

    private Button sinaBtn, qqBtn, cancelBtn;

    protected void initPopuptWindow()
    {
        screenWidth = getWindowManager().getDefaultDisplay().getWidth();
        screenHeight = getWindowManager().getDefaultDisplay().getHeight();
        int h = (int) (screenHeight / 2.15);
        View popupWindowView = getLayoutInflater().inflate(
            R.layout.weibo_popwindow, null, false);
        sinaBtn = (Button) popupWindowView.findViewById(R.id.sina_weibo_btn);
        sinaBtn.setOnClickListener(onClickListener);

        qqBtn = (Button) popupWindowView.findViewById(R.id.qq_weibo_btn);
        qqBtn.setOnClickListener(onClickListener);

        cancelBtn = (Button) popupWindowView.findViewById(R.id.cancel_btn);
        cancelBtn.setOnClickListener(onClickListener);
        popupWindowView.setFocusable(true);
        popupWindowView.setFocusableInTouchMode(true);
        popupWindowView.setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event)
            {
                if (keyCode == KeyEvent.KEYCODE_BACK && popupWindow.isShowing())
                {
                    popupWindow.dismiss();
                    popupWindow = null;
                    return true;
                }
                return false;
            }
        });

        popupWindow = new PopupWindow(popupWindowView, screenWidth, h, true);

        popupWindow.setAnimationStyle(R.style.PopupAnimation);
    }

    public void showAlertLogoutDlg(String title, String msg, String posTitle,
        String nagativeTitle)
    {
        final Dialog dialog = new Dialog(this, R.style.custom_dialog);
        dialog.setContentView(R.layout.dialog_double_alert);
        ((TextView) dialog.findViewById(R.id.dialog_content)).setText(msg);
        ((Button) dialog.findViewById(R.id.left_btn)).setText(nagativeTitle);
        ((Button) dialog.findViewById(R.id.right_btn)).setText(posTitle);
        dialog.findViewById(R.id.left_btn).setOnClickListener(
            new OnClickListener() {
                @Override
                public void onClick(View v)
                {
                    dialog.cancel();
                }
            });
        dialog.findViewById(R.id.right_btn).setOnClickListener(
            new OnClickListener() {
                @Override
                public void onClick(View v)
                {
                    logoutUser();
                    dialog.cancel();
                }
            });
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    // 注销用户
    private void logoutUser()
    {

        isLogoutClick = true;
        url = ConfigUtilHelper.logoutUrl + "?&id=" + ConfigUtilHelper.loginId
            + "&auth=" + ConfigUtilHelper.loginAuth + "&mobile="
            + ConfigUtilHelper.getMobile(this) + "&ostype=" + 2;
        showProgressDlg(getString(R.string.notice),
            getString(R.string.logouting));
    }

    /**
     * 询问是否登录上次登录的新浪账户窗口
     * 
     * @param title
     * @param msg
     * @param posTitle
     * @param nagativeTitle
     */
    public void showAlertDlg_sina(String title, String msg, String posTitle,
        String nagativeTitle)
    {
        new AlertDialog.Builder(this)
            .setTitle(title)
            .setMessage(msg)
            .setIcon(android.R.drawable.ic_dialog_info)
            .setCancelable(true)
            .setPositiveButton(posTitle, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    // TODO Auto-generated method stub
                    positiveDowork_sina();
                }
            })
            .setNegativeButton(nagativeTitle,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        // TODO Auto-generated method stub
                        nagativeDoWork_sina();
                    }

                }).create().show();
    }

    /**
     * 点击是进入上次登录新浪账户
     */
    public void positiveDowork_sina()
    {
        // TODO Auto-generated method stub
        String access = ConfigUtil.getSinaToken(this);
        if (access != null)
        {
            if (access.split("&").length == 3)
            {
                String sina_access_token = access.split("&")[0];
                AccessToken accessToken = new AccessToken(sina_access_token,
                    CONSUMER_SECRET);
                Weibo.getInstance().setAccessToken(accessToken);
            }
        }
        gotoShare();
    }

    /**
     * 点击否进入新的授权窗口
     */
    public void nagativeDoWork_sina()
    {
        // TODO Auto-generated method stub
        if (connectedNetwork())
        {
            sinaShare();
        }
        else
        {
            checkInternet();
        }
    }

    public void showAlertDlg(String title, String msg, String posTitle,
        String nagativeTitle)
    {
        new AlertDialog.Builder(this)
            .setTitle(title)
            .setMessage(msg)
            .setIcon(android.R.drawable.ic_dialog_info)
            .setCancelable(true)
            .setPositiveButton(posTitle, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    // TODO Auto-generated method stub
                    positiveDowork();
                }
            })
            .setNegativeButton(nagativeTitle,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        // TODO Auto-generated method stub
                        nagativeDoWork();
                    }

                }).create().show();
    }

    public void positiveDowork()
    {
        // TODO Auto-generated method stub
        conf.setSinaAccessOAuthToken(sinaAccessToken);
        conf.setSinaAccessOAuthTokenSecret(sinaSccessTokenSecret);
        conf.setQqAccessOAuthToken(qqAccessToken);
        conf.setQqAccessOAuthTokenSecret(qqAccessTokenSecret);
        intent = new Intent(MoreActivity.this, ShareActivity_qq.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    public void nagativeDoWork()
    {
        // TODO Auto-generated method stub
        if (connectedNetwork())
        {
            intent = new Intent(MoreActivity.this, AuthorizationAct.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        else
        {
            checkInternet();
        }
    }

    public void showProgressDlg(String title, String msg)
    {
        final ProgressDialog loadingDlg = new ProgressDialog(this);
        loadingDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        loadingDlg.setTitle(title);
        loadingDlg.setMessage(msg);
        loadingDlg.setIcon(android.R.drawable.ic_dialog_info);
        loadingDlg.setMessage(msg);
        loadingDlg.setCancelable(false);
        loadingDlg.show();
        new Thread() {
            public void run()
            {
                try
                {
                    progressRun();
                }
                catch (Exception e)
                {
                    loadingDlg.dismiss();
                }
                loadingDlg.dismiss();
            }
        }.start();
        loadingDlg
            .setOnDismissListener(new DialogInterface.OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog)
                {
                    // TODO Auto-generated method stub
                    doWork();
                }
            });
    }

    public void progressRun()
    {
        if (isLogoutClick)
        {
            result = ConfigUtilHelper.request(url);
            if (result == null || result.equals(""))
            {
                return;
            }
            try
            {
                JSONObject joson = new JSONObject(result);
                status = joson.getInt("status");
                message = joson.getString("message");
            }
            catch (Exception e)
            {

            }
        }
        else
        {
            share();
        }

    }

    public void doWork()
    {
        if (isLogoutClick)
        {
            isLogoutClick = false;
            switch (status)
            {
            case 0:
                CmccDataStatistics.Comm_Logout(this,
                    ConfigUtilHelper.getMobile(this));
                mDatabaseAdapter.open_user();
                mDatabaseAdapter.deleteAllUserData();
                mDatabaseAdapter.close_user();
                SharedPreferences mSharedPreferences = getSharedPreferences(
                    ConfigUtilHelper.INFO_VISIBLE_PREFS, Context.MODE_PRIVATE);
                Editor edit = mSharedPreferences.edit();
                edit.putBoolean(ConfigUtilHelper.IS_LOGIN, false);
                edit.commit();
                isLogin = false;
                loginImage.setImageResource(R.drawable.regist_login);
                loginTxt.setText(getString(R.string.login_title));
                app.clearContent();

                ConfigUtilHelper.saveAutoLogin(MoreActivity.this, false);
                ConfigUtilHelper.saveRmbPwdFlag(MoreActivity.this, false);
                ConfigUtilHelper
                    .savePwdSharedPreferences(MoreActivity.this, "");
                Toast.makeText(MoreActivity.this, R.string.logout_success,
                    Toast.LENGTH_SHORT).show();
                break;
            case 401:
                showSingleAlertDlg(getString(R.string.notice), message,
                    getString(R.string.dialog_close));
                break;
            case 406:
                showSingleAlertDlg(getString(R.string.notice), message,
                    getString(R.string.dialog_close));
                break;
            }
            return;
        }

        if (isAuth)
        {
            askGotoLastUser();
            return;
        }
        else
        {
            intent = new Intent(MoreActivity.this, AuthorizationAct.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        }
        if (connectedNetwork())
        {
            startActivity(intent);
        }
        else
        {
            checkInternet();
        }
    }

    private void askGotoLastUser()
    {
        showAlertDlg(getString(R.string.dialog_warning),
            getString(R.string.dialog_goto_last_user),
            getString(R.string.dialog_yes), getString(R.string.dialog_no));
    }

    // **************************新浪oAuth2.0认证******************************************************

    // *************************参数****************************
    Weibo mWeibo = Weibo.getInstance();
    private static final String FROM = "xweibo";

    // 设置appkey及appsecret，如何获取新浪微博appkey和appsecret请另外查询相关信息，此处不作介绍
    private static final String CONSUMER_KEY = "2932222159";// 替换为开发者的appkey，例如"1646212960";
    private static final String CONSUMER_SECRET = "b14395ca4c5242e2d17c05b4afb260b8";// 替换为开发者的appkey，例如"94098772160b6f8ffc1315374d8861f9";

    // private final String sina_AppKey = "2932222159";
    // private final String sina_AppSecret = "b14395ca4c5242e2d17c05b4afb260b8";
    // *****************************************************

    private void sinaShare()
    {
        mWeibo.setupConsumerConfig(CONSUMER_KEY, CONSUMER_SECRET);

        // Oauth2.0
        // 隐式授权认证方式
        mWeibo.setRedirectUrl(ConfigUtil.callBackUrl);// 此处回调页内容应该替换为与appkey对应的应用回调页
        // 对应的应用回调页可在开发者登陆新浪微博开发平台之后，
        // 进入我的应用--应用详情--应用信息--高级信息--授权设置--应用回调页进行设置和查看，
        // 应用回调页不可为空

        mWeibo.authorize(MoreActivity.this, new AuthDialogListener());
    }

    private void gotoShare()
    {
        try
        {
            share2weibo(getString(R.string.weibo_default_words), "");
            Intent i = new Intent(MoreActivity.this, ShareActivity.class);
            startActivity(i);
        }
        catch (WeiboException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {

        }
    }

    class AuthDialogListener implements WeiboDialogListener
    {

        @Override
        public void onComplete(Bundle values)
        {
            String uid = values.getString("uid");
            String token = values.getString("access_token");
            String expires_in = values.getString("expires_in");
            AccessToken accessToken = new AccessToken(token, CONSUMER_SECRET);
            accessToken.setExpiresIn(expires_in);
            Weibo.getInstance().setAccessToken(accessToken);

            // access_token过期时间
            long expires_out = accessToken.getExpiresIn();
            String access = token + "&" + uid + "&" + expires_out;
            ConfigUtil.saveSinaToken(getApplicationContext(), access);
            gotoShare();
        }

        @Override
        public void onError(DialogError e)
        {
            Toast.makeText(getApplicationContext(), "授权失败：" + e.getMessage(),
                Toast.LENGTH_LONG).show();
            if (ConfigUtilHelper.debug)
            {
                Log.i(TAG, "授权失败:" + e.getMessage());
            }
        }

        @Override
        public void onCancel()
        {
            Toast.makeText(getApplicationContext(), "授权取消", Toast.LENGTH_LONG)
                .show();
            if (ConfigUtilHelper.debug)
            {
                Log.i(TAG, "onCancel");
            }
        }

        @Override
        public void onWeiboException(WeiboException e)
        {
            Toast.makeText(getApplicationContext(), "授权异常：" + e.getMessage(),
                Toast.LENGTH_LONG).show();
            if (ConfigUtilHelper.debug)
            {
                Log.i(TAG, "授权异常：" + e.getMessage());
            }
        }
    }

    private void share2weibo(String content, String picPath)
        throws WeiboException
    {
        Weibo weibo = Weibo.getInstance();
        weibo.share2weibo(this, weibo.getAccessToken().getToken(), weibo
            .getAccessToken().getSecret(), content, picPath);
    }

    private String getPublicTimeline(Weibo weibo) throws MalformedURLException,
        IOException, WeiboException
    {
        String url = Weibo.SERVER + "statuses/public_timeline.json";
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", Weibo.getAppKey());
        String rlt = weibo.request(this, url, bundle, "GET",
            mWeibo.getAccessToken());
        return rlt;
    }

    private String upload(Weibo weibo, String source, String file,
        String status, String lon, String lat) throws WeiboException
    {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", source);
        bundle.add("pic", file);
        bundle.add("status", status);
        if (!TextUtils.isEmpty(lon))
        {
            bundle.add("lon", lon);
        }
        if (!TextUtils.isEmpty(lat))
        {
            bundle.add("lat", lat);
        }
        String rlt = "";
        String url = Weibo.SERVER + "statuses/upload.json";
        try
        {
            rlt = weibo.request(this, url, bundle, Utility.HTTPMETHOD_POST,
                mWeibo.getAccessToken());
        }
        catch (WeiboException e)
        {
            throw new WeiboException(e);
        }
        return rlt;
    }

    private String update(Weibo weibo, String source, String status,
        String lon, String lat) throws WeiboException
    {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", source);
        bundle.add("status", status);
        if (!TextUtils.isEmpty(lon))
        {
            bundle.add("lon", lon);
        }
        if (!TextUtils.isEmpty(lat))
        {
            bundle.add("lat", lat);
        }
        String rlt = "";
        String url = Weibo.SERVER + "statuses/update.json";
        rlt = weibo.request(this, url, bundle, Utility.HTTPMETHOD_POST,
            mWeibo.getAccessToken());
        return rlt;
    }

    // **************************新浪oAuth2.0认证******************************************************
}